/*
*  Copyright (c) 2006-2020, Chukie
*  
*  SPDX-License-Identifier: Apache-2.0
*  
*  @file     : uart_frame_sample.c
*  
*  @brief    : 
*  
*  
*  Change Logs:
*  Date           Author          Notes
*  2020-09-22     zhaocj          the first version
*/
/* Includes -----------------------------------------------------------------*/
#include <uart_frame.h>
#include <stdlib.h>
#include <stdio.h>
#define DBG_TAG "[UART-SAMPLE]"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

/* Private typedef ----------------------------------------------------------*/
uint8_t sample_running = 0;
rt_thread_t thread = NULL;
struct uart_instance instance;
/* Private define -----------------------------------------------------------*/
#define UART_DEVICE_NAME        "uart3"
/* Private variables --------------------------------------------------------*/
/* Extern variables ---------------------------------------------------------*/
/* Private function prototypes ----------------------------------------------*/


/* Public function prototypes -----------------------------------------------*/
static int user_hook(uart_instance_t instance, uint8_t *data, size_t len)
{
    LOG_D("%s:Rcv %dB data",__FUNCTION__,len);
    return len;
}

static void uart_frame_sample_entry(void *param)
{
    int ret = 0;
    struct uart_frame_config config = UART_FRAME_DEFAULT_CONFIG;
    uint8_t *buf = rt_malloc(1024);
    if (!buf)
    {
        LOG_E("Can't malloc buf!");
        return ;
    }

    if(RT_EOK != uart_frame_init(&instance,UART_DEVICE_NAME,&config,user_hook)){
        LOG_E("Init uart frame failed!");
        rt_free(buf);
        return ;
    }
    rt_thread_delay(1000);
    LOG_I("Start...");
    sample_running = 1;
    while (sample_running)
    {
        ret = uart_frame_read(&instance,buf,1024);
        if (ret > 0)
        {
            uart_frame_write(&instance,buf,ret);
        }
        rt_thread_mdelay(5);
    }
    rt_free(buf);
}


static void uart_frame_sample(uint8_t argc, char **argv)
{
    if (argc < 2)
    {
        rt_kprintf("Usage:\n");
        rt_kprintf("    %s start/stop\n",__FUNCTION__);
    }
    if (0 == rt_strcmp(argv[1], "start"))
    {
        if(sample_running){
            rt_kprintf("Uart frame sample is running, please stop it firstly!\n");
            return;
        }
        
        thread = rt_thread_create("uart-sample", uart_frame_sample_entry, RT_NULL, 1528, 6, 10);
        if (!thread)
        {
            LOG_E("Create thread failed!");
            return ;
        }
        if(RT_EOK != rt_thread_startup(thread)){
            LOG_E("Startup uart-frame-sample failed!");
        }
    }
    else if (0 == rt_strcmp(argv[1], "stop"))
    {
        sample_running = 0;
    }
    else
    {
        rt_kprintf("Usage:\n");
        rt_kprintf("    %s start/stop\n",__FUNCTION__);
    }

}
MSH_CMD_EXPORT(uart_frame_sample, start/stop uart frame sample);
/* End of file****************************************************************/

